package service

import (
	"gitee.com/sansaniot/ssiot-core/msg/sms/model"
	"strconv"

	"gitee.com/sansaniot/ssiot-core/httpmvc/service"
	"gitee.com/sansaniot/ssiot-core/logger"
	"gitee.com/sansaniot/ssiot-core/msg/email"
	"gitee.com/sansaniot/ssiot-core/msg/sms"
	"gorm.io/gorm"

	"ssnotify/common/constant"
	"ssnotify/common/dto"
	"ssnotify/common/utils"
	"ssnotify/internal/notify/models"
	"ssnotify/internal/notify/models/command"
	"ssnotify/internal/notify/models/query"
)

type NotifySender struct {
	notifySender *models.NotifySender
	service.Service
}

func (e *NotifySender) SetNotifySenderModel(model *models.NotifySender) *NotifySender {
	e.notifySender = model
	return e
}

func (e *NotifySender) PostSettings(c *command.NotifySenderPostReq) error {
	err := e.notifySender.Upsert(&c.Settings)
	RefreshSettings(e.Orm)
	return err
}

func (e *NotifySender) DelSettings(c *command.NotifySenderDelReq) error {
	err := e.notifySender.ModMap(e.notifySender, map[string]interface{}{"value": ""}, dto.MakeCondition(query.SysNotifySenderGetReq{IdIn: c.Ids}))
	RefreshSettings(e.Orm)
	return err
}

func RefreshSettings(db *gorm.DB) {
	settings := make([]models.NotifySender, 0)
	var err error
	if err = db.Model(&settings).Find(&settings).Limit(-1).Offset(-1).Error; err != nil {
		logger.Error(err)
	}
	var ee any
	smsAccessKeyId, smsAccessKeySecret, smsSignName, vendor := "", "", "", ""
	emailHost, emailPort, emailUsername, emailPassword := "", 0, "", ""
	for _, v := range settings {
		ee = nil
		switch v.Id {
		case "sms.accessKey":
			if len(v.Value) > 0 {
				smsAccessKeyId, ee = utils.AesDecrypt(v.Value, constant.SALTKEY)
			}
		case "sms.accessSecret":
			if len(v.Value) > 0 {
				smsAccessKeySecret, ee = utils.AesDecrypt(v.Value, constant.SALTKEY)
			}
		case "sms.signName":
			smsSignName = v.Value
		case "sms.vendor":
			vendor = v.Value
		case "email.host":
			emailHost = v.Value
		case "email.port":
			emailPort, _ = strconv.Atoi(v.Value)
		case "email.username":
			emailUsername = v.Value
		case "email.password":
			if len(v.Value) > 0 {
				emailPassword, ee = utils.AesDecrypt(v.Value, constant.SALTKEY)
			}
		}
		if ee != nil {
			logger.Errorf("解密%s值失败", v.Id)
		}
	}

	//短信服务参数
	if len(smsAccessKeyId) > 0 && len(smsAccessKeySecret) > 0 {
		constant.SmsConfig = model.SMSConfig{
			AccessKeyId:     smsAccessKeyId,
			AccessKeySecret: smsAccessKeySecret,
			SignName:        smsSignName,
			Vendor:          vendor,
		}
		_ = sms.InitSMSConfig(&constant.SmsConfig)
	} else {
		_ = sms.InitSMSConfig(nil)
	}

	//邮件服务参数
	if len(emailHost) > 0 && len(emailUsername) > 0 && len(emailPassword) > 0 {
		constant.EmailConfig = email.EmailConfig{
			Host:     emailHost,
			Port:     emailPort,
			Username: emailUsername,
			Password: emailPassword,
		}
		_ = email.InitConfig(&constant.EmailConfig)
	} else {
		_ = email.InitConfig(nil)
	}

	logger.Info("刷新通知网关配置")
}
